package com.atguigu.flinkState;

import com.atguigu.been.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author wky
 * @create 2021-07-19-9:35
 */
//为每个key设置的状态值 每个key独立 不影响
    //检测传感器的水位线值，如果连续的两个水位线差值超过10，就输出报警。
public class State_Keyed_Value {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();

        senv.setParallelism(1);
        DataStreamSource<String> source = senv.socketTextStream("hadoop102", 9999);
        SingleOutputStreamOperator<WaterSensor> map = source.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });
        KeyedStream<WaterSensor, String> keyedStream = map.keyBy(WaterSensor::getId);
        //检测传感器的水位线值，如果连续的两个水位线差值超过10，就输出报警。
        keyedStream.process(new KeyedProcessFunction<String, WaterSensor, String>() {
            //设置状态值
            private ValueState<Integer> state;

            @Override
            public void open(Configuration parameters) throws Exception {
                //初始化 防止空指针异常 加载时间的问题
                state=getRuntimeContext().getState(new ValueStateDescriptor<Integer>("st",Integer.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //赋值
               Integer lastVc =  state.value()==null ? 0 : state.value();
               if (Math.abs(value.getVc()-lastVc)>10){
                   out.collect(value.toString());
                   System.out.println("警报!!!!!!!!");
               }
               //更新
               state.update(value.getVc());


            }
        }).print();
        senv.execute();


    }
}
